
import VueStore from '@/store/index.js';
import { isSameDay, formatDate } from '@/utils/common.js';
import OceandataApi from "@/server/data/oceanData.js";

export class DataNavigator {//
    constructor(dates, depth, target, type) {
        this.dates = dates;
        this.depth = depth;
        this.target = target;
        this.type = type;
    }
    async PostDataTime(dates, depth, target, type, date) {
        //当前时间 
        let time = VueStore.state.data.date;
        if (time) {
            time += ' 20:00:00';
        } else {
            //需要手动减去8小时
            if (date) {
                time = formatDate(new Date(new Date(date).getTime() - 3600000 * 8));
            } else {
                time = formatDate(new Date(new Date().getTime() - 3600000 * 8));
            }
        }
        const getSerialdataResult = await OceandataApi.getSerialdata(dates, depth, target, time, type);
        if (getSerialdataResult.isOk) {
            let localTime = [{ 'data_time': getSerialdataResult.data.data_time }]
            //存入当前数据时间
            VueStore.commit('data/setDataTime', { dataName: type, dataTime: VueStore.state.data.OFDataTime[type] == '' ? getSerialdataResult.data.data_time : VueStore.state.data.OFDataTime[type] });
            let arr = [];
            //防止返回的urlList为空报错
            arr = getSerialdataResult.data.history_list ? arr.concat(getSerialdataResult.data.history_list) : arr;
            arr = getSerialdataResult.data.data_time ? arr.concat(localTime) : arr;
            arr = getSerialdataResult.data.forcast_list ? arr.concat(getSerialdataResult.data.forcast_list) : arr;
            return arr;
        } else {
            console.log(`获取${type}数据出错`)
        }
    }
}


export function getClosestDateTime(name, date) {
    const timestamp = date.getTime();
    let dataList = VueStore.state.data.OFeatureList[name].filter(
        (data) => {
            return isSameDay(date, new Date(data.data_time));
        }
    );
    dataList = dataList.length === 0 ? VueStore.state.data.OFeatureList[name] : dataList;
    let temp = 999999999999;
    let idx = 0;
    for (let i = 0; i < dataList.length; i++) {
        const dataTimeStamp = new Date(dataList[i].data_time).getTime();
        const difference = Math.abs(timestamp - dataTimeStamp);
        idx = difference < temp ? i : idx;
        temp = difference < temp ? difference : temp;
    }

    const closestDate = new Date(dataList[idx].data_time);
    const urlDate = new Date(closestDate.getTime() - 3600000 * 8);
    const year = urlDate.getFullYear();
    const month = String(urlDate.getMonth() + 1).padStart(2, "0");
    const day = String(urlDate.getDate()).padStart(2, "0");
    const hours = String(urlDate.getHours()).padStart(2, "0");
    const minutes = String(urlDate.getMinutes()).padStart(2, "0");
    return {
        date: `${year}${month}${day}`,
        time: `${hours}${minutes}`,
        formatDate: formatDate(closestDate, 'yyyy-MM-dd HH:mm:ss'),
    };
}